package com.elancom.framework.commons.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarFile;

/**
 * @author elancom
 * @date 2012-7-1
 */
public class JarValidator {
	public static void startCheck() throws IOException {
		String jarDir = "C:\\Users\\Administrator\\.m2\\repository";

		File file = new File(jarDir);
		List<JarFile> jars = getAllJarFiles(file);

		StringBuilder ok = new StringBuilder();
		StringBuilder err = new StringBuilder();
		for (JarFile f : jars) {
			if (check(f)) {
				ok.append("正确").append(f.getName()).append("\n");
			} else {
				err.append("损坏").append(f.getName()).append("\n");
			}
		}

		if (err.length() == 0) {
			System.err.println("所有jar都OK");
		} else {
			System.out.println(err);
		}

	}

	private static boolean check(JarFile f) throws IOException {
		try {
			f.getManifest();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	private static List<JarFile> getAllJarFiles(File file) throws IOException {
		List<JarFile> jars = new ArrayList<>();
		getJarFiles(jars, file);
		return jars;
	}

	private static void getJarFiles(List<JarFile> jars, File file) throws IOException {
		if (file.isDirectory()) {
			for (File f : file.listFiles()) {
				getJarFiles(jars, f);
			}
		} else {
			if (file.getName().lastIndexOf(".jar") == file.getName().length() - 4) {
				jars.add(new JarFile(file));
			}
		}
	}

	public static void main(String[] args) throws IOException {
		startCheck();
	}
}
